package hgin

import (
	"bytes"
	"encoding/json"
	"github.com/gin-gonic/gin"
	"net/http"
	"time"
	"vitepress-serve/internal/common/errs"
)

// ApiReq 接口请求数据绑定
func ApiReq[T any](ctx *gin.Context) (v T) {
	return Bind[T](ctx)
}

// ApiRes 接口响应报文
func ApiRes(ctx *gin.Context, v any) {
	var data = gin.H{}
	if v == nil {
		v = gin.H{}
	}
	switch v.(type) {
	case error:
		e := errs.NewF(v.(error))
		data = gin.H{"errno": e.Code, "errmsg": e.Message, "host_time": HostTime(), "body": gin.H{}}
	default:
		data = gin.H{"errno": "00000", "errmsg": "ok", "host_time": HostTime(), "body": v}
	}
	b, _ := JsonMarshal(data)

	resBody := string(b)
	ctx.Set(CtxSetResBody, resBody) // 用于日志记录上下文 响应报文

	ctx.Data(http.StatusOK, "application/json; charset=UTF-8", b)
	ctx.Abort()
}

// JsonMarshal 不转义符号 & < >
func JsonMarshal(v any) (b []byte, err error) {
	bf := bytes.NewBuffer([]byte{})
	jsonEncoder := json.NewEncoder(bf)
	jsonEncoder.SetEscapeHTML(false)
	err = jsonEncoder.Encode(v)
	b = bf.Bytes()
	return
}

// HostTime 14位服务器时间  如：20221009210500
func HostTime() string {
	return time.Now().Local().Format("20060102150405")
}
